// miniprogram/pages/pay/pay.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.showCount = 0;  //显示数目
    let actionOptions = wx.parseJSONQueryStrObj(this.options);
    let title = actionOptions.title;

    if (!title || title == "undefined" || title == "null"){
      actionOptions.title = "";
    }

    this.actionOptions = actionOptions;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var actionOptions = Object.assign({},this.actionOptions);
    var title = actionOptions.title;

    if (title){
      wx.setNavigationBarTitle({ title: title });
    }

    wx.processDataQueues([actionOptions]);

    this.parseAction();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.showCount += 1;

    let { action,params } = this.actionOptions;

    switch(action){
      case "payment":{

        break;
      }

      case "map":{

        if (this.showCount > 1){
          wx.navigateBack({
            delta:1
          });
        }

        break;
      }

      default:{

      }

    }



  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  parseAction:function(){
    let { action,params } = this.actionOptions;

    switch(action){
      case "payment":{
        this.startPayment(params);
        break;
      }

      case "map":{
        this.openLocation(params);
        break;
      }

      case "scan": {
        this.scanCode(params);
        break;
      }

      default:{

      }

    }


  },



  // 支付：开始


  /**
   * 开始支付
   */
  startPayment: function (params) {
    let title = this.actionOptions.title;
    let { nextLocation, succLocation, failLocation, timeStamp, ...payParams } = params;

    if (wx.isInvalidQueryValue(succLocation)) {
      succLocation = nextLocation;
    }

    if (wx.isInvalidQueryValue(failLocation)) {
      failLocation = nextLocation;
    }

    let payOpt = {
      timeStamp: timeStamp.toString(),
      ...payParams,
      success: (res) => {
        this.navToNextLocationForPay(succLocation, res, title);
      },
      fail: (res) => {
        var errMsg = res.errMsg;

        if (typeof errMsg == "string") {
          var isCancel = errMsg.search(/cancel/i) >= 0;

          if (isCancel) {
            this.navToNextLocationForPay(null, res, title);
            return
          }
        }

        if (errMsg){
          errMsg = "支付失败:" + errMsg;
          wx.showToast({
            title: errMsg,
            icon: "none"
          });
        }

        this.navToNextLocationForPay(failLocation, res, title);
      }
    };


    wx.requestPayment(payOpt);
  },

  /**
   * 导航到下一个页面
   */
  navToNextLocationForPay: function (nextLoca, info,title) {
    if (nextLoca) {
      wx.letWebviewNavToInterLocat(nextLoca, "OutPage");
      let pageUrl = wx.stringifyUrl({
        url: "/pages/outPage/outPage",
        searchParams: {
          title: title || "支付结果"
        }
      });
      wx.redirectTo({
        url: pageUrl
      });
    } else {
      wx.navigateBack({
        delta: 1
      })
    }
  },


  // 支付：结束



  // 地图：开始


  /**
   * 打开位置
   */
  openLocation: function (params) {
    params.latitude = parseFloat(params.latitude || '0');
    params.longitude = parseFloat(params.longitude || '0');
    wx.openLocation(params);
  },


  // 地图：结束




  // 扫码：开始

  /**
   * 扫码
   *
   * @param  params : {nextLocation,succLocation,failLocation,key}
   * @property nextLocation ？: urlString | Location    下一步跳转的位置
   * @property succLocation ？: urlString | Location    成功时跳转的位置；如果没有设置该值，会取 nextLocation 的值
   * @property failLocation ？: urlString | Location    失败时跳转的位置；如果没有设置该值，会取 nextLocation 的值
   * @property key ？: string     配置扫码结果的 key ；默认值："scanresult"； 扫码的结果会拼接到 回调位置 Location 的 hash 参数中，参数的 key 由该配置选项指定；
   */
  scanCode: function (params){
    let title = this.actionOptions.title;
    let { nextLocation, succLocation, failLocation, key, ...payParams } = params;
    if(wx.isInvalidQueryValue(key)){
      key = "scanresult";
    }

    if (wx.isInvalidQueryValue(succLocation)) {
      succLocation = nextLocation;
    }

    if (wx.isInvalidQueryValue(failLocation)) {
      failLocation = nextLocation;
    }

    wx.scanCode({
      ...params,
      success: (res) => {
        this.navToNextLocationForScan(succLocation,key, res);
      },
      fail: (res) => {
        var errMsg = res.errMsg;

        if (typeof errMsg == "string") {
          var isCancel = errMsg.search(/cancel/i) >= 0;

          if (isCancel) {
            this.navToNextLocationForScan(null,key ,res);
            return
          }
        }

        if (errMsg) {
          errMsg = "扫苗失败:" + errMsg;
          wx.showToast({
            title: errMsg,
            icon: "none"
          });
        }

        this.navToNextLocationForScan(failLocation,key, res);
      }
    })

  },




  navToNextLocationForScan: function (nextLocation,key, params) {

    if (params && typeof params == "object"){
      params.id = (new Date()).getTime();
    }

    if (nextLocation && typeof nextLocation == "object") {
      let query = nextLocation.query || {};
      query[key] = JSON.stringify(params);

      wx.letWebviewNavToInterLocat(nextLocation);

    } else if (nextLocation) {

      nextLocation = {
        href: nextLocation,
        addHashParams:{
          [key]: params
        }
      };

      wx.launchPageURL = nextLocation
    }



    wx.navigateBack({
      delta: 1
    });

  },
  // 扫码：结束



})
